/**
 * use Message
 */
import type { App, DirectiveBinding } from 'vue'

interface CopyParams {
  text: string // 复制的文本
  message: string // 复制成功后的提示
}

const vCopy = {
  mounted(
    el: Element & {
      $value: CopyParams
      handler: EventListenerOrEventListenerObject
    },
    { value }: DirectiveBinding<CopyParams>,
  ) {
    el.$value = value
    el.handler = () => {
      const { text, message } = el.$value
      const textDom = document.createElement('input')
      textDom.readOnly = true
      textDom.value = text
      document.body.appendChild(textDom)
      textDom.select()
      textDom.setSelectionRange(0, textDom.value.length)
      const result = document.execCommand('Copy')
      if (result) {
        Message.success(message || '复制成功')
      }
      document.body.removeChild(textDom)
    }
    el.addEventListener('click', el.handler)
  },
  updated(el: any, { value }: any) {
    el.$value = value
  },
  unmounted(el: any) {
    el.removeEventListener('click', el.handler)
  },
}

export function registerVCopy(app: App) {
  app.directive('copy', vCopy)
}

export default vCopy
